package cn.hdu.liang;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

public class FreemarkerDemo {
    //搭建Freemarker
    public static void main(String[] args) throws IOException, TemplateException {
        //配置对象
        Configuration conf = new Configuration();
        //模板路径
        String dir = "/home/liang/WorkSpace/IDEA/Projects/Freemarker/src/main/webapp/";
        //导入模板目录
        conf.setDirectoryForTemplateLoading(new File(dir));
        //获取模板
        Template template = conf.getTemplate("freemarker.html");

        //数据
        Map root = new HashMap();
        root.put("world", null);

        Person p = new Person();
        p.setId(23);
        p.setName("马琳");
        root.put("p", p);

        List<String> persons = new ArrayList<>();
        persons.add("马琳");
        persons.add("王励勤");
        persons.add("王皓");
        root.put("persons", persons);

        Map map = new HashMap();
        map.put("ml", "马琳");
        map.put("wlq", "王励勤");
        map.put("wh", "王皓");
        root.put("map", map);

        List<Map> maps = new ArrayList<>();
        Map pms1 = new HashMap();
        pms1.put("ml", "马琳");
        pms1.put("wlq", "王励勤");
        pms1.put("wh", "王皓");
        maps.add(pms1);
        Map pms2 = new HashMap();
        pms2.put("zjk", "张继科");
        pms2.put("ml", "马龙");
        pms2.put("xx", "许昕");
        maps.add(pms2);
        root.put("maps", maps);

        root.put("cut_time", new Date());
        //输出流
        Writer out = new FileWriter(new File(dir + "hello.ftl"));
        //生成开始
        template.process(root, out);

        System.out.println("生成完毕");

        //关闭流
        out.close();
    }
}
